package com.fast.controller;

import com.fast.entity.User;
import com.fast.jpa.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpSession;

/**
 * Created by Le-Le on 2017/6/21.
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = "/login",produces = "application/json; charset=UTF-8")
    public String login(HttpSession session,final User user) {
        boolean falg = true;
        logger.info("username={},password={}",user.getUsername(),user.getPassword());
        User newUser = userRepository.findOne(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                criteriaQuery.where(criteriaBuilder.equal(root.get("username"),user.getUsername()));
                return null;
            }
        });
        if (newUser == null) {
            falg = false;
            return "用户名不存在，登录失败";
        }

        if (!newUser.getPassword().equals(user.getPassword())) {
            falg = false;
            return "密码错误，登录失败";
        }
        if (falg) {
            session.setAttribute("user",newUser);
        }
        return "登录成功";
    }
}
